﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Daniel Vaughan. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2010-11-20 13:28:27Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;

using DanielVaughan.Collections;
using DanielVaughan.Windows.Controls.Design;

using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace DanielVaughan.Windows.Controls
{
    [ContentProperty("Buttons")]
    public class AppBar : ItemsControl, IApplicationBar
    {
        readonly ApplicationBar applicationBar = new ApplicationBar();
        bool loaded;

        public AppBar()
        {
            Loaded += HandleLoaded;
            ItemVisibilityProperty = DependencyProperty.RegisterAttached(
                                        "ItemVisibility",
                                        typeof(Visibility),
                                        typeof(UserControl),
                                        new PropertyMetadata(HandleItemVisibilityChanged));
        }

        void HandleLoaded(object sender, RoutedEventArgs e)
        {
            if (loaded)
            {
                return;
            }

            if (AutoAttach)
            {
                Attach();
            }

            loaded = true;
        }

        public void Attach()
        {
            var page = this.GetVisualAncestors<PhoneApplicationPage>()
                                                .FirstOrDefault();

            var pivot = this.GetVisualAncestors<Pivot>().FirstOrDefault();
            if (pivot != null)
            {
                pivot.SelectionChanged -= pivot_SelectionChanged;
                pivot.SelectionChanged += pivot_SelectionChanged;
                UpdateApplicationBar(pivot);
            }
            else if (page != null)
            {
                page.ApplicationBar = applicationBar;
                Build();
            }
        }

        void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateApplicationBar((Pivot)sender);
        }

        protected virtual void UpdateApplicationBar(Pivot pivot)
        {
            var page = this.GetVisualAncestors<PhoneApplicationPage>().LastOrDefault();

            if (pivot == null || page == null)
            {
                return;
            }

            bool assignBar = false;

            if (pivot.SelectedItem == DataContext)
            {
                assignBar = true;
            }
            else
            {
                var frameworkElement = pivot.SelectedItem as FrameworkElement;
                if (frameworkElement != null
                        && frameworkElement.DataContext == DataContext)
                {
                    assignBar = true;
                }
            }

            if (assignBar)
            {
                page.ApplicationBar = applicationBar;
                Build();
            }
            else if (page.ApplicationBar == applicationBar)
            {
                page.ApplicationBar = null;
            }
        }

        #region AutoAttach

        public static DependencyProperty AutoAttachProperty
            = DependencyProperty.Register(
                "AutoAttach",
                typeof(bool),
                typeof(AppBar),
                new PropertyMetadata(true));

        public bool AutoAttach
        {
            get
            {
                return (bool)GetValue(AutoAttachProperty);
            }
            set
            {
                SetValue(AutoAttachProperty, value);
            }
        }

        #endregion

        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);
            if (loaded)
            {
                Build();
            }
        }

        bool building;

        void Build()
        {
            if (building)
            {
                return;
            }

            try
            {
                building = true;
                BuildAux();
            }
            finally
            {
                building = false;
            }
        }

        void BuildAux()
        {
            applicationBar.Buttons.Clear();
            applicationBar.MenuItems.Clear();

            foreach (FrameworkElement item in Items.OfType<FrameworkElement>())
            {
                RegisterForNotification("Visibility", item);
            }

            var buttonList = (from button in Items.Where(notUIElementOrVisibleFunc)
                                        .OfType<IApplicationBarIconButtonProvider>()
                              select button.Button).ToList();

            if (buttonList.Count > 4)
            {
                buttonList = buttonList.Take(4).ToList();
            }

            applicationBar.Buttons.AddRange(buttonList);

            var menuItemList = (from item
                                 in Items.Where(notUIElementOrVisibleFunc)
                                        .OfType<IApplicationBarMenuItemProvider>()
                                select item.MenuItem).ToList();

            applicationBar.MenuItems.AddRange(menuItemList);
        }

        readonly Func<object, bool> notUIElementOrVisibleFunc
            = x =>
            {
                var element = x as UIElement;
                return element == null || element.Visibility == Visibility.Visible;
            };

        #region ItemVisibility

        readonly DependencyProperty ItemVisibilityProperty;

        void HandleItemVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (loaded)
            {
                Build();
            }
        }

        public Visibility ItemVisibility
        {
            get
            {
                return (Visibility)GetValue(ItemVisibilityProperty);
            }
            set
            {
                SetValue(ItemVisibilityProperty, value);
            }
        }

        #endregion

        void RegisterForNotification(
            string propertyName,
            FrameworkElement element)
        {
            var expression = element.GetBindingExpression(ItemVisibilityProperty);
            if (expression == null)
            {
                Binding binding = new Binding(propertyName) { Source = element };
                element.SetBinding(ItemVisibilityProperty, binding);
            }
        }

        //		static void RegisterForNotification(
        //			string propertyName,
        //			FrameworkElement element,
        //			PropertyChangedCallback callback)
        //		{
        //			Binding binding = new Binding(propertyName) { Source = element };
        //			var property = DependencyProperty.RegisterAttached(
        //								"ChangeListenerAttached" + propertyName,
        //								typeof(object),
        //								typeof(UserControl),
        //								new PropertyMetadata(callback));
        //
        //			element.SetBinding(property, binding);
        //		}

        //		void OnItemVisibilityChanged(
        //			DependencyObject d, DependencyPropertyChangedEventArgs e)
        //		{
        //			if (loaded)
        //			{
        //				Build();
        //			}
        //		}

        public IList Buttons
        {
            get
            {
                return Items;
            }
        }

        public IList MenuItems
        {
            get
            {
                return Items;
            }
        }

        #region IsMenuEnabled

        public static readonly DependencyProperty IsMenuEnabledProperty
            = DependencyProperty.RegisterAttached(
                "IsMenuEnabled",
                typeof(bool),
                typeof(AppBar),
                new PropertyMetadata(true, HandleMenuEnabledChanged));

        static void HandleMenuEnabledChanged(
            DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AppBar bar;
            if (e.NewValue != e.OldValue && (bar = d as AppBar) != null)
            {
                bar.applicationBar.IsMenuEnabled = (bool)e.NewValue;
            }
        }

        public event EventHandler<ApplicationBarStateChangedEventArgs> StateChanged = delegate {};

        public bool IsMenuEnabled
        {
            get
            {
                return (bool)GetValue(IsMenuEnabledProperty);
            }
            set
            {
                SetValue(IsMenuEnabledProperty, value);
            }
        }

        #endregion

        #region IsVisible

        public static readonly DependencyProperty IsVisibleProperty
            = DependencyProperty.RegisterAttached(
                "IsVisible",
                typeof(bool),
                typeof(AppBar),
                new PropertyMetadata(true, HandleIsVisibleChanged));

        static void HandleIsVisibleChanged(
            DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AppBar bar;
            if (e.NewValue != e.OldValue
                && (bar = d as AppBar) != null)
            {
                bar.applicationBar.IsVisible = (bool)e.NewValue;
            }
        }

        public bool IsVisible
        {
            get
            {
                return (bool)GetValue(IsVisibleProperty);
            }
            set
            {
                SetValue(IsVisibleProperty, value);
            }
        }

        #endregion

        #region BarOpacity

        public static DependencyProperty BarOpacityProperty
            = DependencyProperty.Register(
                "BarOpacity",
                typeof(double),
                typeof(AppBar),
                new PropertyMetadata(1.0, HandleBarOpacityChanged));

        static void HandleBarOpacityChanged(
            DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var appBar = (AppBar)d;
            appBar.applicationBar.Opacity = (double)e.NewValue;
        }

        public double BarOpacity
        {
            get
            {
                return (double)GetValue(BarOpacityProperty);
            }
            set
            {
                SetValue(BarOpacityProperty, value);
            }
        }

        #endregion

        #region BackgroundColor

        public static DependencyProperty BackgroundColorProperty
            = DependencyProperty.Register(
                "BackgroundColor",
                typeof(Color),
                typeof(AppBar),
                new PropertyMetadata(HandleBackgroundColorChanged));

        static void HandleBackgroundColorChanged(
            DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var appBar = (AppBar)d;
            appBar.applicationBar.BackgroundColor = (Color)e.NewValue;
        }

        public Color BackgroundColor
        {
            get
            {
                return (Color)GetValue(BackgroundColorProperty);
            }
            set
            {
                SetValue(BackgroundColorProperty, value);
            }
        }

        #endregion

        #region ForegroundColor

        public static DependencyProperty ForegroundColorProperty
            = DependencyProperty.Register(
                "ForegroundColor",
                typeof(Color),
                typeof(AppBar),
                new PropertyMetadata(HandleForegroundColorChanged));

        static void HandleForegroundColorChanged(
            DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var appBar = (AppBar)d;
            appBar.applicationBar.ForegroundColor = (Color)e.NewValue;
        }

        public Color ForegroundColor
        {
            get
            {
                return (Color)GetValue(ForegroundColorProperty);
            }
            set
            {
                SetValue(ForegroundColorProperty, value);
            }
        }

        #endregion

        #region Mode

        public static DependencyProperty ModeProperty
            = DependencyProperty.Register(
                "Mode",
                typeof(ApplicationBarMode),
                typeof(AppBar),
                new PropertyMetadata(ApplicationBarMode.Default, HandleModeChanged));

        static void HandleModeChanged(
            DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var appBar = (AppBar)d;
            appBar.applicationBar.Mode = (ApplicationBarMode)e.NewValue;
        }

        public ApplicationBarMode Mode
        {
            get
            {
                return (ApplicationBarMode)GetValue(ModeProperty);
            }
            set
            {
                SetValue(ModeProperty, value);
            }
        }

        #endregion

        public double DefaultSize
        {
            get
            {
                return applicationBar != null ? applicationBar.DefaultSize : 72.0;
            }
        }

        public double MiniSize
        {
            get
            {
                return applicationBar != null ? applicationBar.MiniSize : 30.0;
            }
        }
    }
}
